package org.jeecg.modules.sxaq.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sxaq.utils.RabbitMQConstant;
import org.jeecg.modules.system.controller.SysUserController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 注册处理（已废弃，私有云在追加用户时，调用共有云完成注册）
 * @Author: DHC
 * @Date:  2020-12-01
 */
@Slf4j
@RabbitComponent(value = "localRegisterListener")
public class RegisterRabbitMqListener extends BaseRabbiMqHandler<BaseMap> {
    @Autowired
    private SysUserController sysUserController;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Value("${sxaq.factoryCode}")
    private String factoryCode;
    @Autowired
    private RabbitMqClient rabbitMqClient;

    @RabbitListener(concurrency = "2-10", bindings = {@QueueBinding(value = @Queue(value = RabbitMQConstant.LOCAL_REGISTER_QUEUE + "${sxaq.factoryCode}", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = RabbitMQConstant.LOCAL_REGISTER_EXCHANGE, type = "topic"),
            key = RabbitMQConstant.LOCAL_REGISTER_KEY + "${sxaq.factoryCode}")})
    public void onMessage(String message) {
        log.info("-------收到云端下发的用户注册信息-------");
        try {
            JSONObject object = JSONObject.parseObject(message);
            Result<SysUser> result1 = new Result<SysUser>();
            JSONObject jsonObject = object.getJSONObject("registerObject");
            SysUser sysUser = JSON.parseObject(jsonObject.toJSONString(), new TypeReference<SysUser>() {
            });
            String push_token = jsonObject.getString("pushToken");
            String client_type = jsonObject.getString("clientType");
            Result result = sysUserController.userRegister2(sysUser, push_token, client_type);

            String orgCodeText = "";
            //如果当前用户无选择部门 查看部门关联信息
            List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
            if (departs != null && departs.size() > 0) {
                String orgCode = departs.get(0).getOrgCode();
                orgCodeText = departs.get(0).getDepartName();

                if (oConvertUtils.isEmpty(sysUser.getOrgCode())) {
                    sysUser.setOrgCode(orgCode);
                    sysUserService.updateUserDepart(sysUser.getId(), orgCode);
                }
                sysUser.setOrgCodeTxt(orgCodeText);
            }

            // 发送消息给共有云
            JSONObject cloudMap = new JSONObject();
            if (result.isSuccess()) {
                SysUser user = (SysUser) result.getResult();
                user.setOrgCodeTxt(orgCodeText);
                result1.setResult(user);
                cloudMap.put("registerObject", result1);
            } else {
                cloudMap.put("registerObject", Result.error("用户注册失败！"));
            }
            cloudMap.put("factoryCode", factoryCode);
            cloudMap.put("workNo", sysUser.getWorkNo());
            cloudMap.put("phone", sysUser.getPhone());

            rabbitMqClient.sendMessageToExchange(RabbitMQConstant.CLOUD_REGISTER_EXCHANGE, RabbitMQConstant.CLOUD_REGISTER_KEY + factoryCode, cloudMap.toJSONString());
            log.info("-------上报云端下发的注册结果-------");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("-------收到云端下发的用户注册信息-------" + e);
        }
    }
}
